package org.example;

import java.util.ArrayList;
import java.util.List;

public class Solution19 {
    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> result = new ArrayList<>();

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }

        // 行
        int m = matrix.length;
        // 列
        int n = matrix[0].length;

        // 1. 初始化边界,代表矩阵的边界
        int top = 0;
        int bottom = m - 1;
        int left = 0;
        int right = n - 1;

        // 2. 遍历矩阵
        while (top <= bottom && left <= right) {
            // 从左到右遍历顶部行
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;

            // 从上到下遍历右侧列
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--;

            // 从右到左遍历底部行
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;
            }

            // 从下到上遍历左侧列
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }
        }

        return result;
    }
}
